<?php

/**
 * 请求日志
 */

namespace App\Models;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class RequestLog extends Model
{
    const UPDATED_AT = null;
    protected $connection = 'mysql';
    protected $table = 'request_logs';
    protected $guarded = ['id'];


    /**
     * 写入日志
     * @param $data
     * @return bool
     */
    public function insertLog($data)
    {
        return DB::connection($this->connection)
            ->table($this->getLogTable())
            ->insert($data);
    }

    /**
     * 获取表名
     * @param int $createTime
     * @return string
     */
    public function getLogTable($createTime = 0)
    {
        $createTime || $createTime = time();
        $table = 'request_logs_' . date('Ym', $createTime);
        $this->createTable($table);
        return $table;
    }


    /**
     * 创建表
     * @param string $table
     * @return string
     */
    private function createTable($table)
    {
        return Cache::rememberForever('ai_request_logs_table_' . $table, function () use ($table) {
            if (!(Schema::connection($this->connection)->hasTable($table))) {
                $sql = "CREATE TABLE `{$table}` (
                         `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                         `uri` varchar(100) NOT NULL DEFAULT '' COMMENT '请求uri',
                         `method` varchar(10) NOT NULL DEFAULT '' COMMENT '请求方式',
                         `params` text NOT NULL COMMENT '请求参数',
                         `user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
                         `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                         PRIMARY KEY (`id`),
                         KEY `uri` (`uri`),
                         KEY `user_id` (`user_id`),
                         KEY `created_at` (`created_at`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
                DB::connection($this->connection)->statement($sql);
            }
            return $table;
        });
    }
}
